package com.anrongtec.zcpt.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.adapter.common.CommonAdapter;
import com.anrongtec.zcpt.adapter.common.ViewHolder;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.constant.JsonDataRestult;
import com.anrongtec.zcpt.constant.URLConstants;
import com.anrongtec.zcpt.model.AppModel;
import com.anrongtec.zcpt.model.Comment;
import com.anrongtec.zcpt.model.PageList;
import com.anrongtec.zcpt.utils.DividerDecoration;
import com.anrongtec.zcpt.utils.GsonUtil;
import com.anrongtec.zcpt.utils.HeaderAndFooterWrapper;
import com.anrongtec.zcpt.utils.HttpUtil;
import com.anrongtec.zcpt.utils.ToastShow;
import com.anrongtec.zcpt.widget.EmptyWrapper;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;
import okhttp3.Response;

public class AppCommentsActivity extends BaseActivity {
    private RecyclerView recycler_comment;

    private AppModel appModel;//当前app

    private CommonAdapter<Comment> adapter;

    private int currentPage = 1, totalPage;//当前查询页,   所有页

    private List<Comment> totalComment, comments;//所有评论,  当前查询到的评论

    private EmptyWrapper<Comment> empty, empty1;

    private boolean loading = false;//是否正在加载中

    private static final int REFRESH = 1;
    private static final int NO_DATA = 2;
    private Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH:
                    empty.notifyDataSetChanged();
                    break;

                case NO_DATA:
                    empty.setEmptyView(R.layout.empty_view);
                    recycler_comment.setAdapter(empty);
                    break;

                default:
                    break;
            }
            loading = false;
            loadingView.setVisibility(View.GONE);
        }
    };

    private LinearLayoutManager linearLayoutManager;

    private HeaderAndFooterWrapper footer;

    private View loadingView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleShow(true);
        initData();
        setContentView(R.layout.activity_app_comments);
        initViews();

        getComments(1);
    }

    @Override
    protected void onCreateCustomToolBar(Toolbar toolbar) {
        super.onCreateCustomToolBar(toolbar);
        toolbar.setTitle(appModel.getAppName());
    }

    @Override
    protected void initViews() {
        totalComment = new ArrayList<Comment>();
        recycler_comment = (RecyclerView) findViewById(R.id.recyclerview_app_comments_list);
        linearLayoutManager = new LinearLayoutManager(AppCommentsActivity.this, LinearLayoutManager.VERTICAL, false);
        recycler_comment.setLayoutManager(linearLayoutManager);
        adapter = new CommonAdapter<Comment>(this, R.layout.item_person_comment, totalComment) {
            @Override
            protected void convert(ViewHolder holder, Comment t, int position) {
                holder.setRating(R.id.rating_item_person_comment, t.getScore());
                holder.setText(R.id.tv_item_person_comment_content, t.getContent());
                holder.setText(R.id.tv_item_person_comment_time, t.getTime());
            }
        };
        loadingView = LayoutInflater.from(this).inflate(R.layout.loading_view, null);
        loadingView.setVisibility(View.GONE);

        footer = new HeaderAndFooterWrapper(adapter);
        footer.addFootView(loadingView);

        empty = new EmptyWrapper(footer);
        empty.setEmptyView(R.layout.loading_view);

        recycler_comment.setAdapter(empty);
        recycler_comment.addItemDecoration(new DividerDecoration(this));
        recycler_comment.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState != RecyclerView.SCROLL_STATE_IDLE) {
                    return;
                }
                //是否滑动到最后
                if (!(linearLayoutManager.findLastCompletelyVisibleItemPosition() >= linearLayoutManager.getItemCount() - 1)) {
                    return;
                }
                //当前页数小于总页数
                if (!(currentPage < totalPage)) {
                    return;
                }
                //是否正在加载中
                if (loading) {
                    return;
                }
                loadMore();

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

        });
    }

    @Override
    protected void initData() {
        appModel = (AppModel) getIntent().getSerializableExtra(Constant.DATA);
    }

    /**
     * 获取当前应用的评论信息
     */
    private void getComments(int page) {

        String json = GsonUtil.toQueryCommentJson(appModel.getAppPackName(), appModel.getRemoteVersionCode(), page);
        HttpUtil.post(json, new StringCallback() {
            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
                JsonDataRestult<PageList<Comment>> result = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<PageList<Comment>>>(){}.getType());
                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    currentPage = result.getData().getPage();
                    totalPage = result.getData().getTotalPage();
                    comments = result.getData().getComments();
                    totalComment.addAll(comments);

                    if (totalComment.size() != 0) {
                        handler.sendEmptyMessage(REFRESH);
                    }else {
                        handler.sendEmptyMessage(NO_DATA);
                    }
                }else {
                    ToastShow.shortMessage(result.getRetMsg());
                }
            }
        });
    }

    /**
     * 加载更多
     */
    protected void loadMore() {
        loading = true;
        loadingView.setVisibility(View.VISIBLE);
        getComments(++currentPage);
    }

}

